package com.solo.UserService.impl;

import com.solo.UserService.UserService;
import com.solo.entity.User;
import com.solo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/*
 * FileName: UserServiceImpl.java
 * Description: UserService实现类
 * Author:   woolflighthouse@163.com
 * Date:     2025-11-23 7:23
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public User login(String username, String password) {
        try {
            // 方式1：先查询用户，再验证密码
            User user = userMapper.findByUsername(username);
            if (user != null && user.getPassword().equals(password)) {
                return user;
            }

            // 方式2：直接使用用户名和密码查询（推荐，减少一次数据库交互）
            // return userMapper.findByUsernameAndPassword(username, password);

            return null;
        } catch (Exception e) {
            throw new RuntimeException("登录验证失败", e);
        }
    }

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public boolean register(User user) {
        try {
            // 检查用户名是否已存在
            User existingUser = userMapper.findByUsername(user.getUsername());
            if (existingUser != null) {
                return false; // 用户名已存在
            }

            // 插入新用户
            int result = userMapper.insert(user);
            return result > 0;
        } catch (Exception e) {
            throw new RuntimeException("用户注册失败", e);
        }
    }
}
